document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const form = document.getElementById('registerForm');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const emailInput = document.getElementById('email');
    const emailCodeInput = document.getElementById('emailCode');
    const captchaInput = document.getElementById('captcha');
    const sendCodeBtn = document.getElementById('sendCodeBtn');
    const registerBtn = document.getElementById('registerBtn');
    const agreeTermsCheckbox = document.getElementById('agreeTerms');

    // 发送验证码
    sendCodeBtn.addEventListener('click', function() {
        if (!emailInput.value) {
            showError(emailInput, '请输入邮箱地址');
            return;
        }

        if (!validateEmail(emailInput.value)) {
            showError(emailInput, '邮箱格式不正确');
            return;
        }

        sendCodeBtn.disabled = true;
        let countdown = 60;
        sendCodeBtn.innerHTML = `<span>${countdown}秒后重试</span>`;

        const timer = setInterval(() => {
            countdown--;
            sendCodeBtn.innerHTML = `<span>${countdown}秒后重试</span>`;

            if (countdown <= 0) {
                clearInterval(timer);
                sendCodeBtn.disabled = false;
                sendCodeBtn.textContent = '获取验证码';
            }
        }, 1000);

        fetch("/erb/api/auth/email/send-code?email=" + document.getElementById("email").value, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            credentials: "include"
        }).then(response => {
            if (response.ok) {
                showAlert("验证码已发送至邮箱，请查收", 'success', 2000);
            }
        }).catch(error => {
            showError(emailInput, "验证码发送失败，请重试");
            console.error(error);
        })
    });

    // 实时表单验证
    passwordInput.addEventListener('input', validatePassword);
    confirmPasswordInput.addEventListener('input', validateConfirmPassword);
    emailInput.addEventListener('input', validateEmailInput);
    emailCodeInput.addEventListener('input', validateEmailCode);
    captchaInput.addEventListener('input', validateCaptcha);
    agreeTermsCheckbox.addEventListener('change', validateTerms);

    // 表单提交处理
    form.addEventListener('submit', function(e) {
        e.preventDefault();

        // 验证所有字段
        const isUsernameValid = validateUsername();
        const isPasswordValid = validatePassword();
        const isConfirmValid = validateConfirmPassword();
        const isEmailValid = validateEmailInput();
        const isCodeValid = validateEmailCode();
        const isCaptchaValid = validateCaptcha();
        const isTermsValid = validateTerms();

        if (isUsernameValid && isPasswordValid && isConfirmValid &&
            isEmailValid && isCodeValid && isCaptchaValid && isTermsValid) {

            // 模拟注册请求
            registerBtn.disabled = true;
            registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';

            setTimeout(() => {
                // 这里应该是实际的AJAX请求
                alert('注册成功！即将跳转到登录页面');
                form.reset();
                registerBtn.disabled = false;
                registerBtn.innerHTML = '<span>立即注册</span><i class="fas fa-arrow-right"></i>';
            }, 2000);
        } else {
            // 如果有错误，给用户提示
            showError(registerBtn, '请检查表单中的错误');
            registerBtn.classList.add('shake');
            setTimeout(() => {
                registerBtn.classList.remove('shake');
            }, 500);
        }
    });

    // 验证函数
    function validatePassword() {
        const value = passwordInput.value;
        if (!value) {
            showError(passwordInput, '密码不能为空');
            return false;
        } else if (value.length < 6 || value.length > 20) {
            showError(passwordInput, '密码长度应为6-20位');
            return false;
        } else {
            showSuccess(passwordInput);
            return true;
        }
    }

    function validateConfirmPassword() {
        const value = confirmPasswordInput.value;
        if (!value) {
            showError(confirmPasswordInput, '请确认密码');
            return false;
        } else if (value !== passwordInput.value) {
            showError(confirmPasswordInput, '两次输入的密码不一致');
            return false;
        } else {
            showSuccess(confirmPasswordInput);
            return true;
        }
    }

    function validateEmailInput() {
        const value = emailInput.value.trim();
        if (!value) {
            showError(emailInput, '邮箱不能为空');
            return false;
        } else if (!validateEmail(value)) {
            showError(emailInput, '邮箱格式不正确');
            return false;
        } else {
            showSuccess(emailInput);
            return true;
        }
    }

    function validateEmailCode() {
        const value = emailCodeInput.value.trim();
        if (!value) {
            showError(emailCodeInput, '验证码不能为空');
            return false;
        } else if (!/^[A-Za-z0-9]{6}$/.test(value)) {
            showError(emailCodeInput, '验证码应为6位字符');
            return false;
        } else {
            showSuccess(emailCodeInput);
            return true;
        }
    }

    function validateCaptcha() {
        const value = captchaInput.value.trim().toUpperCase();
        const regexp = /^[A-Z0-9]{4}$/;
        if (!value) {
            showError(captchaInput, '验证码不能为空');
        } else if (!regexp.test(value)) {
            showError(captchaInput, '验证码应为4位字母或数字');
        } else {
            showSuccess(captchaInput);
        }
        return true;
    }

    function validateTerms() {
        if (!agreeTermsCheckbox.checked) {
            agreeTermsCheckbox.parentElement.classList.add('error');
            return false;
        } else {
            agreeTermsCheckbox.parentElement.classList.remove('error');
            return true;
        }
    }

    // 辅助函数
    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
});

function showError(input, message) {
    const formGroup = input.parentElement.parentElement;
    const errorMessage = formGroup.querySelector('.error-message');

    errorMessage.textContent = message;
    errorMessage.style.display = 'block';
    input.classList.add('error');
    input.classList.remove('success');
}

function showSuccess(input) {
    const formGroup = input.parentElement.parentElement;
    const errorMessage = formGroup.querySelector('.error-message');

    errorMessage.style.display = 'none';
    input.classList.remove('error');
    input.classList.add('success');
}
